#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);

    this->setWindowTitle("张嘉旺的智能家居");
    server=new QTcpSocket();
    server->connectToHost(QHostAddress("47.121.24.16"),1884);

    connect(server,&QTcpSocket::connected,[this]()
    {
      QMessageBox::information(this,"连接提示","连接服务器成功");

    });
    connect(server,&QTcpSocket::disconnected,[this]()
    {
      QMessageBox::warning(this,"连接提示","服务器连接断开");

    });

    connect(server,&QTcpSocket::readyRead,this, &Widget::server_reply_slot);





}

Widget::~Widget()
{
    delete ui;
}


void Widget::on_pushButton_clicked()
{
    pid=ui->id->text();

    QString pwd=ui->password->text();
    QJsonObject obj;
    obj.insert("username",pid);
    obj.insert("password",pwd);

    QByteArray ba=QJsonDocument(obj).toJson();
    ba.insert(0,0x50);
    server->write(ba);



}
void Widget::server_reply_slot()
{
    QByteArray ba=server->readAll();

    QJsonObject obj=QJsonDocument::fromJson(ba).object();
    if(obj.value("cmd").toString()=="register")
    {

     if(obj.value("result").toString()=="success")
     {

      QMessageBox::information(this,"注册提示","注册成功");



     }
     else if(obj.value("result").toString()=="exist")
     {
          QMessageBox::warning(this,"注册提示","注册失败");



     }



    }

     else if(obj.value("cmd").toString()=="login")
    {
        if(obj.value("result").toString()=="usernoexist")
        {

        QMessageBox::warning(this,"登录提示","用户不存在");



        }
        else if(obj.value("result").toString()=="success")
        {

          smarthome * st=new   smarthome(pid);

            server->disconnect(SIGNAL(readyRead()));
            server->disconnect(SIGNAL(disconnected()));

            st->show();
            this->close();


        }
        else if(obj.value("result").toString()=="passworderr")
        {

               QMessageBox::warning(this,"登录提示","密码错误");


        }



    }




}

void Widget::on_login_clicked()
{
    pid=ui->id->text();

    QString pwd=ui->password->text();
    QJsonObject obj;
    obj.insert("username",pid);
    obj.insert("password",pwd);

    QByteArray ba=QJsonDocument(obj).toJson();
    ba.insert(0,0x60);
    server->write(ba);






}
